package com.magicalcoder.pigeon.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by hzhedongyu on 2017/5/27.
 */
public class ServerWorkerPool {
    private Logger logger = LoggerFactory.getLogger(ServerWorkerPool.class);

    private static volatile ServerWorkerPool pool;
    //线程池 用来控制服务端处理客户端请求量 避免压垮服务端
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)
            , new ThreadFactory() {
                    private AtomicInteger count = new AtomicInteger(0);
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setName("Pigeon-ServerWorkerPool-"+count.incrementAndGet());
                    return thread;
                }
            }
            , new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    logger.error("服务端线程池已满，拒绝再放入");
                }
    });

    private ServerWorkerPool() {
    }

    public static ServerWorkerPool get(){
        if(pool == null){
            synchronized (ServerWorkerPool.class){
                if(pool==null){
                    pool = new ServerWorkerPool();
                }
            }
        }
        return pool;
    }

    public void accept(Runnable runnable){
        threadPoolExecutor.execute(runnable);
    }


}
